<template>
  <div class="theater-app">
    <!-- API状态指示器 -->
    <div v-if="!apiConnected" class="api-status-banner">
      <div class="status-content">
        <span class="status-icon">⚠️</span>
        <span>{{ apiError || 'API服务连接中...' }}</span>
        <button class="retry-btn" @click="checkApiConnection">重试</button>
      </div>
    </div>

    <div class="container">
      <header class="top-nav">
        <div class="nav-left">
          <button class="back-btn" @click="goBack">
            <span class="icon">←</span>
          </button>
          <h1 class="theater-name">
            {{ theaterData.title || '剧场编辑器' }}
          </h1>
          <!-- 数据状态指示器 -->
          <div class="data-status" v-if="hasUserData">
            <span class="status-indicator" :class="dataSourceType">
              {{ dataSourceText }}
            </span>
            <span class="last-updated" v-if="lastUpdateTime">
              {{ formatTime(lastUpdateTime) }}
            </span>
          </div>
        </div>
        <div class="nav-right">
          <!-- 🔧 显示/隐藏编辑界面切换 -->
          <button
            class="btn btn-outline"
            @click="toggleEditMode"
            v-if="!showEditInterface && !isIntelligentGenerating"
          >
            ✏️ 显示编辑界面
          </button>
          <button
            class="btn btn-outline"
            @click="toggleEditMode"
            v-if="showEditInterface && !hasUserData"
          >
            👁️ 隐藏编辑界面
          </button>

          <button class="btn btn-warning" @click="confirmReset" v-if="hasUserData">
            🔄 重置数据
          </button>
          <button class="btn ai-btn" @click="showIntelligentGenerator" :disabled="!apiConnected">
            🧠 {{ hasAIGeneratedData ? '重新生成' : 'AI智能生成' }}
          </button>
          <button class="btn btn-secondary" @click="saveToLocalStorage" v-if="hasUserData">
            💾 本地保存
          </button>
          <button class="btn btn-primary" @click="saveScript" v-if="hasUserData">
            💾 保存剧情
          </button>
          <button class="btn btn-success" @click="publishTheater" v-if="hasUserData">
            🚀 发布剧场
          </button>
        </div>
      </header>

      <!-- AI生成进度 -->
      <div v-if="isIntelligentGenerating" class="generation-progress">
        <div class="progress-header">
          <h3>🤖 AI正在智能生成您的剧场...</h3>
          <span class="progress-percentage">{{ Math.round(generationProgress.progress) }}%</span>
        </div>
        <div class="progress-bar-container">
          <div class="progress-bar" :style="{ width: `${generationProgress.progress}%` }"></div>
        </div>
        <div class="progress-info">
          <span class="current-stage">{{
            getStageDisplayName(generationProgress.current_stage)
          }}</span>
          <span class="stage-message">{{ generationProgress.message }}</span>
        </div>
        <div class="generation-preview" v-if="generationProgress.partial_result">
          <h4>生成预览：</h4>
          <pre>{{ JSON.stringify(generationProgress.partial_result, null, 2) }}</pre>
        </div>
      </div>

      <!-- 🔧 欢迎引导界面 - 没有显示编辑界面时显示 -->
      <div v-if="!showEditInterface && !isIntelligentGenerating" class="welcome-guide">
        <div class="guide-content">
          <div class="guide-animation">
            <div class="guide-icon">🎭</div>
            <div class="sparkles">
              <span class="sparkle sparkle-1">✨</span>
              <span class="sparkle sparkle-2">⭐</span>
              <span class="sparkle sparkle-3">💫</span>
            </div>
          </div>

          <h2>剧场创作工作台</h2>
          <p class="guide-subtitle">选择您喜欢的创作方式开始构建剧场体验</p>

          <div class="creation-options">
            <div class="option-card ai-option">
              <div class="option-header">
                <span class="option-icon">🧠</span>
                <h3>AI智能生成</h3>
              </div>
              <p class="option-desc">描述您的想法，AI将自动创建完整的剧场系统</p>
              <div class="option-features">
                <span class="feature-tag">🎯 智能角色</span>
                <span class="feature-tag">📖 自动剧情</span>
                <span class="feature-tag">⚔️ 技能体系</span>
              </div>
              <button
                class="option-btn ai-btn"
                @click="showIntelligentGenerator"
                :disabled="!apiConnected"
              >
                🧠 开始AI生成
              </button>
            </div>

            <div class="option-card manual-option">
              <div class="option-header">
                <span class="option-icon">✏️</span>
                <h3>手动创建</h3>
              </div>
              <p class="option-desc">使用编辑界面，从零开始构建您的剧场世界</p>
              <div class="option-features">
                <span class="feature-tag">🎨 自由创作</span>
                <span class="feature-tag">🔧 精细控制</span>
                <span class="feature-tag">📝 逐步构建</span>
              </div>
              <button class="option-btn btn-primary" @click="startManualCreation">
                ✏️ 开始手动创作
              </button>
            </div>
          </div>

          <div class="additional-options" v-if="hasStoredData">
            <div class="stored-data-notice">
              <span class="notice-icon">📁</span>
              <span class="notice-text">检测到之前保存的数据</span>
              <button class="btn btn-secondary" @click="loadStoredData">
                📁 恢复之前的数据
              </button>
            </div>
          </div>

          <div class="guide-tips">
            <h4>💡 创作提示</h4>
            <ul>
              <li><strong>AI生成</strong> - 适合快速创建完整剧场，AI会处理所有细节</li>
              <li><strong>手动创建</strong> - 适合精细化控制，可以按自己的想法逐步构建</li>
              <li><strong>混合创作</strong> - 可以先AI生成基础框架，再手动调整细节</li>
              <li><strong>数据保护</strong> - 创作过程中数据会自动保护，避免意外丢失</li>
            </ul>
          </div>

          <div class="api-status-check" v-if="!apiConnected">
            <div class="status-warning">
              <span class="warning-icon">⚠️</span>
              <span class="warning-text">AI服务连接中，手动创作功能可正常使用</span>
              <button class="retry-small-btn" @click="checkApiConnection">重试连接</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 🔧 主要内容区域 - 根据showEditInterface控制显示 -->
      <div class="content-area" v-if="showEditInterface && !isIntelligentGenerating">
        <aside class="sidebar left-sidebar">
          <div class="sidebar-header">
            <h2>📚 剧情节点</h2>
            <button class="ai-btn" @click="showScriptGenerator" :disabled="!apiConnected">
              🤖 AI剧情
            </button>
          </div>

          <div class="node-tree">
            <div class="root-node">{{ theaterData.title || '剧场标题' }}</div>
            <div
              v-for="node in scriptNodes"
              :key="node.id"
              class="node-item"
              :class="{ active: node.id === activeNodeId }"
              @click="selectNode(node.id)"
            >
              📄 {{ node.title }}
            </div>
            <div v-if="scriptNodes.length === 0" class="empty-state-small">
              <span class="empty-icon">📝</span>
              <span class="empty-text">暂无剧情节点</span>
            </div>
          </div>

          <button class="add-node" @click="addNewNode">➕ 添加节点</button>
        </aside>

        <main class="main-content">
          <!-- 🔧 剧场基本信息编辑 -->
          <div class="theater-info-section" v-if="!theaterData.title">
            <h3>🎭 剧场基本信息</h3>
            <div class="form-row">
              <div class="form-group">
                <label class="form-label">剧场名称</label>
                <input
                  v-model="theaterData.title"
                  type="text"
                  class="form-input"
                  placeholder="输入剧场名称"
                  @input="onDataChange"
                />
              </div>
              <div class="form-group">
                <label class="form-label">时代背景</label>
                <input
                  v-model="theaterData.era"
                  type="text"
                  class="form-input"
                  placeholder="如：现代、古代、未来"
                  @input="onDataChange"
                />
              </div>
            </div>
            <div class="form-group">
              <label class="form-label">剧场描述</label>
              <textarea
                v-model="theaterData.description"
                class="form-input"
                rows="3"
                placeholder="描述您的剧场背景和主题..."
                @input="onDataChange"
              ></textarea>
            </div>
          </div>

          <!-- 节点编辑区 -->
          <div v-if="currentNode" class="node-editor">
            <input
              v-model="currentNode.title"
              type="text"
              class="node-title"
              placeholder="输入节点标题"
              @input="onDataChange"
            />

            <div class="editor-toolbar">
              <button class="toolbar-btn" @click="formatText('bold')">
                <span class="bold">𝐁</span>
              </button>
              <button class="toolbar-btn" @click="formatText('italic')">
                <span class="italic">𝐼</span>
              </button>
              <div class="toolbar-divider"></div>
              <button
                class="toolbar-btn ai-optimize-btn"
                @click="optimizeContent"
                :disabled="!apiConnected"
              >
                🤖
              </button>
            </div>

            <div
              ref="editorRef"
              class="editor-content"
              contenteditable="true"
              v-html="currentNode.content"
              @input="updateContent"
              :placeholder="currentNode.content ? '' : '开始编写剧情内容...'"
            ></div>
          </div>

          <!-- 空状态提示 -->
          <div v-else class="main-empty-state">
            <div class="empty-state-content">
              <span class="empty-icon">📄</span>
              <h3>还没有剧情节点</h3>
              <p>点击左侧"添加节点"开始创建您的剧情</p>
              <button class="btn btn-primary" @click="addNewNode">
                ➕ 创建第一个节点
              </button>
            </div>
          </div>

          <!-- 角色设置区域 -->
          <div v-if="currentCharacter && currentNode" class="character-settings">
            <h3>🎭 {{ currentCharacter.name }} 的设置</h3>

            <div class="settings-section">
              <h4>预期行为</h4>
              <div class="tags-container">
                <div
                  v-for="(behavior, index) in currentCharacterBehaviors"
                  :key="index"
                  class="tag"
                >
                  {{ behavior }}
                  <span class="tag-remove" @click="removeBehavior(index)">❌</span>
                </div>
                <button class="add-tag" @click="addBehavior">➕ 添加行为</button>
              </div>
            </div>
          </div>
        </main>

        <aside class="sidebar right-sidebar">
          <div class="sidebar-header">
            <h2>👥 角色管理</h2>
            <button class="ai-btn" @click="generateSingleCharacter" :disabled="!apiConnected">
              🤖 AI角色
            </button>
          </div>

          <div class="role-list">
            <div
              v-for="character in characters"
              :key="character.id"
              class="role-item"
              :class="{ active: character.id === activeCharacterId }"
              @click="selectCharacter(character.id)"
            >
              <img :src="character.avatar" :alt="character.name" class="role-avatar" />
              <div class="role-info">
                <div class="role-name">{{ character.name }}</div>
                <div class="role-description">{{ character.description.substring(0, 50) }}...</div>
              </div>
            </div>
            <div v-if="characters.length === 0" class="empty-state-small">
              <span class="empty-icon">👤</span>
              <span class="empty-text">暂无角色</span>
            </div>
          </div>

          <div v-if="currentCharacter" class="attribute-form">
            <h3>👤 角色属性</h3>

            <div class="form-group">
              <label class="form-label">角色名称</label>
              <input
                v-model="currentCharacter.name"
                type="text"
                class="form-input"
                @input="onDataChange"
              />
            </div>

            <div class="form-group">
              <label class="form-label">描述</label>
              <textarea
                v-model="currentCharacter.description"
                class="form-input"
                rows="3"
                @input="onDataChange"
              ></textarea>
            </div>

            <div class="form-group">
              <label class="form-label">特长技能</label>
              <div v-if="normalizedSkills.length > 0" class="skill-tags">
                <div
                  v-for="skill in normalizedSkills"
                  :key="skill"
                  class="skill-tag"
                  :class="{ selected: currentCharacter.selectedSkills.includes(skill) }"
                  @click="toggleSkill(skill)"
                >
                  {{ skill }}
                </div>
              </div>
              <div v-else class="skill-placeholder">
                <p>🔧 技能系统</p>
                <p>使用AI生成或手动添加技能</p>
                <button class="btn btn-secondary btn-small" @click="addManualSkill">
                  ➕ 手动添加技能
                </button>
              </div>
            </div>
          </div>

          <button class="add-role" @click="addNewCharacter">➕ 添加角色</button>
        </aside>
      </div>
    </div>

    <!-- 智能生成模态框 -->
    <div v-if="showIntelligentModal" class="modal-overlay" @click="closeIntelligentModal">
      <div class="modal intelligent-modal" @click.stop>
        <div class="modal-header">
          <h3>🧠 智能剧场生成向导</h3>
          <button class="modal-close" @click="closeIntelligentModal">❌</button>
        </div>
        <div class="modal-body">
          <div class="wizard-step">
            <h4>描述您想要的剧场</h4>
            <textarea
              v-model="intelligentRequest.user_input"
              class="form-input large-textarea"
              rows="4"
              placeholder="例如：我想要一个关于时间旅行的科幻剧场，主角是一个年轻的物理学家，需要回到过去阻止一场灾难..."
            ></textarea>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label class="form-label">复杂度</label>
              <select v-model="intelligentRequest.complexity_level" class="form-input">
                <option value="simple">🌟 简单 - 直观易懂</option>
                <option value="medium">⭐⭐ 中等 - 适度挑战</option>
                <option value="complex">⭐⭐⭐ 复杂 - 深度体验</option>
              </select>
            </div>

            <div class="form-group">
              <label class="form-label">目标受众</label>
              <select v-model="intelligentRequest.target_audience" class="form-input">
                <option value="general">🎯 普通观众</option>
                <option value="young">👨‍🎓 年轻人</option>
                <option value="mature">👨‍💼 成年人</option>
                <option value="family">👨‍👩‍👧‍👦 家庭观众</option>
              </select>
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">特殊要求（可选）</label>
            <input
              v-model="specialRequirementsText"
              type="text"
              class="form-input"
              placeholder="例如：包含解谜元素，多重结局，历史真实性..."
            />
          </div>

          <div class="generation-tips">
            <h5>💡 生成提示：</h5>
            <ul>
              <li>详细描述您的创意想法，AI会根据描述生成相应内容</li>
              <li>可以指定特定的主题、风格、角色类型等</li>
              <li>生成过程大约需要2-5分钟，请耐心等待</li>
              <li><strong>生成的数据会自动保护，避免意外丢失</strong></li>
            </ul>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeIntelligentModal">取消</button>
          <button
            class="btn ai-btn"
            @click="startIntelligentGeneration"
            :disabled="!intelligentRequest.user_input.trim()"
          >
            🧠 开始智能生成
          </button>
        </div>
      </div>
    </div>

    <!-- 🔧 重置确认模态框 -->
    <div v-if="showResetModal" class="modal-overlay" @click="closeResetModal">
      <div class="modal reset-modal" @click.stop>
        <div class="modal-header">
          <h3>⚠️ 确认重置数据</h3>
          <button class="modal-close" @click="closeResetModal">❌</button>
        </div>
        <div class="modal-body">
          <div class="warning-content">
            <div class="warning-icon">🗑️</div>
            <p>您确定要重置所有数据吗？</p>
            <p class="warning-text">此操作将清除当前的所有创作内容，且无法恢复。</p>

            <div class="data-summary">
              <h4>即将清除的数据：</h4>
              <ul>
                <li>剧场信息: {{ theaterData.title || '未设置' }}</li>
                <li>剧情节点: {{ scriptNodes.length }} 个</li>
                <li>角色: {{ characters.length }} 个</li>
                <li>技能系统: {{ availableSkills.length }} 个技能</li>
              </ul>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeResetModal">取消</button>
          <button class="btn btn-danger" @click="executeReset">
            🗑️ 确认重置
          </button>
        </div>
      </div>
    </div>

    <div v-if="showGlobalLoading" class="loading-overlay">
      <div class="loading-content">
        <div class="loading-spinner">🤖</div>
        <p>{{ loadingMessage }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

// 类型定义
interface ScriptNode {
  id: string
  title: string
  content: string
  characterSettings: any
  level: number
}

interface Character {
  id: string
  name: string
  description: string
  avatar: string
  selectedSkills: string[]
}

interface TheaterData {
  title: string
  description: string
  era: string
  location: string
  createdAt: string
  author: string
  plotSummary: string
  features: string[]
}

const API_BASE_URL = 'http://127.0.0.1:8000'
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 120000,
})

// 🔧 核心状态管理
const showEditInterface = ref(false) // 控制是否显示编辑界面
const hasAIGeneratedData = ref(false) // 标记是否有AI生成的数据
const hasManualData = ref(false) // 标记是否有手动创建的数据
const lastUpdateTime = ref<Date | null>(null) // 最后更新时间
const hasStoredData = ref(false) // 是否有存储的数据
const showResetModal = ref(false)

const activeNodeId = ref('node-1')
const activeCharacterId = ref('char-1')
const editorRef = ref<HTMLDivElement>()

const apiConnected = ref(false)
const apiError = ref('')

const showIntelligentModal = ref(false)
const isIntelligentGenerating = ref(false)
const showGlobalLoading = ref(false)
const loadingMessage = ref('')

const intelligentRequest = reactive({
  user_input: '',
  complexity_level: 'medium',
  target_audience: 'general',
  special_requirements: [] as string[],
})

const specialRequirementsText = ref('')

const generationProgress = reactive({
  progress: 0,
  current_stage: '',
  message: '',
  partial_result: null,
})

// 🔧 初始化为完全空的状态
const theaterData = reactive<TheaterData>({
  title: '',
  description: '',
  era: '',
  location: '',
  createdAt: '',
  author: '',
  plotSummary: '',
  features: [],
})

const scriptNodes = reactive<ScriptNode[]>([])
const characters = reactive<Character[]>([])

// 技能数据
const rawSkillsData = ref<any[]>([])
const availableSkills = ref<string[]>([])

// 🔧 计算属性：判断是否有用户数据
const hasUserData = computed(() => {
  return (
    theaterData.title.trim() !== '' ||
    theaterData.description.trim() !== '' ||
    scriptNodes.length > 0 ||
    characters.length > 0 ||
    availableSkills.value.length > 0
  )
})

// 🔧 计算属性：数据来源类型
const dataSourceType = computed(() => {
  if (hasAIGeneratedData.value) return 'ai-generated'
  if (hasManualData.value) return 'manual-created'
  return 'empty'
})

// 🔧 计算属性：数据来源文本
const dataSourceText = computed(() => {
  switch (dataSourceType.value) {
    case 'ai-generated':
      return '✨ AI生成'
    case 'manual-created':
      return '✏️ 手动创建'
    default:
      return ''
  }
})

// 🔧 数据变化监听
const onDataChange = () => {
  lastUpdateTime.value = new Date()
  if (!hasAIGeneratedData.value) {
    hasManualData.value = true
  }
}

// 监听数据变化
watch([theaterData, scriptNodes, characters, availableSkills], () => {
  onDataChange()
}, { deep: true })

// 🔧 页面刷新保护 - 只在有用户数据时生效
const setupPageProtection = () => {
  const handleBeforeUnload = (event: BeforeUnloadEvent) => {
    if (hasUserData.value) {
      const message = '⚠️ 刷新将丢失当前的创作数据，确定要刷新吗？'
      event.preventDefault()
      event.returnValue = message
      return message
    }
  }

  window.addEventListener('beforeunload', handleBeforeUnload)

  onBeforeUnmount(() => {
    window.removeEventListener('beforeunload', handleBeforeUnload)
  })
}

// 🔧 强制清空初始化
const clearAllData = () => {
  console.log('🔄 初始化：清空所有数据')

  // 清空响应式数据
  theaterData.title = ''
  theaterData.description = ''
  theaterData.era = ''
  theaterData.location = ''
  theaterData.createdAt = ''
  theaterData.author = ''
  theaterData.plotSummary = ''
  theaterData.features = []

  scriptNodes.splice(0)
  characters.splice(0)
  rawSkillsData.value = []
  availableSkills.value = []

  // 清空本地存储
  localStorage.removeItem('theater_generated_data')
  localStorage.removeItem('theater_draft')
  localStorage.removeItem('current_theater_data')
  localStorage.removeItem('current_script_nodes')
  localStorage.removeItem('current_characters')
  localStorage.removeItem('current_available_skills')

  // 重置状态
  hasAIGeneratedData.value = false
  hasManualData.value = false
  lastUpdateTime.value = null
  activeNodeId.value = 'node-1'
  activeCharacterId.value = 'char-1'
  showEditInterface.value = false // 默认不显示编辑界面
}

// 🔧 检查是否有存储的数据
const checkStoredData = () => {
  const storedData = localStorage.getItem('theater_generated_data') ||
                   localStorage.getItem('theater_draft')
  hasStoredData.value = !!storedData
}

// 组件挂载
onMounted(async () => {
  console.log('🚀 页面初始化开始')

  // 1. 强制清空所有数据
  clearAllData()

  // 2. 检查存储数据
  checkStoredData()

  // 3. 检查API连接
  await checkApiConnection()

  // 4. 设置页面保护
  setupPageProtection()

  console.log('✅ 页面初始化完成 - 等待用户选择创作方式')
})

// 🔧 格式化时间
const formatTime = (date: Date): string => {
  return date.toLocaleString('zh-CN', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// 🔧 切换编辑界面显示
const toggleEditMode = () => {
  showEditInterface.value = !showEditInterface.value
  console.log(`${showEditInterface.value ? '显示' : '隐藏'}编辑界面`)
}

// 🔧 开始手动创作
const startManualCreation = () => {
  showEditInterface.value = true
  hasManualData.value = true
  lastUpdateTime.value = new Date()

  // 创建默认的剧场基础信息
  if (!theaterData.title) {
    theaterData.createdAt = new Date().toLocaleDateString()
    theaterData.author = '手动创作'
  }

  console.log('✏️ 开始手动创作模式')
}

// 🔧 加载存储的数据
const loadStoredData = () => {
  try {
    console.log('📁 开始加载存储的数据...')

    // 优先加载最新的完整数据
    const completeDataStr = localStorage.getItem('theater_generated_data')
    if (completeDataStr) {
      const completeData = JSON.parse(completeDataStr)
      console.log('📋 发现完整的生成数据:', completeData)

      if (completeData.theater_info) {
        Object.assign(theaterData, completeData.theater_info)
      }

      if (completeData.script_nodes && Array.isArray(completeData.script_nodes)) {
        scriptNodes.splice(0)
        scriptNodes.push(...completeData.script_nodes)
      }

      if (completeData.characters && Array.isArray(completeData.characters)) {
        characters.splice(0)
        characters.push(...completeData.characters)
      }

      if (completeData.available_skills) {
        rawSkillsData.value = Array.isArray(completeData.available_skills)
          ? completeData.available_skills
          : [completeData.available_skills]
        availableSkills.value = normalizeSkillsData(rawSkillsData.value)
      }

      // 判断数据来源
      if (completeData.generated_time) {
        hasAIGeneratedData.value = true
        lastUpdateTime.value = new Date(completeData.generated_time)
      } else {
        hasManualData.value = true
        lastUpdateTime.value = new Date(completeData.saved_time || Date.now())
      }

      showEditInterface.value = true
      console.log('✅ 数据恢复完成')
      return
    }

    // 尝试加载草稿数据
    const draftData = localStorage.getItem('theater_draft')
    if (draftData) {
      const data = JSON.parse(draftData)

      if (data.theaterData) Object.assign(theaterData, data.theaterData)
      if (data.scriptNodes && Array.isArray(data.scriptNodes)) {
        scriptNodes.splice(0)
        scriptNodes.push(...data.scriptNodes)
      }
      if (data.characters && Array.isArray(data.characters)) {
        characters.splice(0)
        characters.push(...data.characters)
      }
      if (data.availableSkills) {
        rawSkillsData.value = Array.isArray(data.availableSkills)
          ? data.availableSkills
          : [data.availableSkills]
        availableSkills.value = normalizeSkillsData(rawSkillsData.value)
      }

      hasManualData.value = true
      lastUpdateTime.value = new Date(data.timestamp || Date.now())
      showEditInterface.value = true
      console.log('✅ 草稿数据恢复完成')
    }

  } catch (error) {
    console.error('❌ 加载存储数据失败:', error)
    alert('加载数据失败，请检查数据格式')
  }
}

// 🔧 技能数据标准化函数（保持原有逻辑）
const normalizeSkillsData = (rawSkills: any[]): string[] => {
  if (!Array.isArray(rawSkills) || rawSkills.length === 0) {
    return []
  }

  const normalizedSkills: string[] = []

  for (let skill of rawSkills) {
    try {
      if (typeof skill === 'string') {
        const trimmedSkill = skill.trim()
        if (trimmedSkill && trimmedSkill.length > 1) {
          normalizedSkills.push(trimmedSkill)
        }
      } else if (skill && typeof skill === 'object') {
        if (skill.skills && Array.isArray(skill.skills)) {
          skill.skills.forEach((subSkill: any) => {
            if (typeof subSkill === 'string' && subSkill.trim().length > 1) {
              normalizedSkills.push(subSkill.trim())
            }
          })
        } else if (skill.name && typeof skill.name === 'string') {
          normalizedSkills.push(skill.name.trim())
        } else if (skill.skill && typeof skill.skill === 'string') {
          normalizedSkills.push(skill.skill.trim())
        }
      }
    } catch (error) {
      console.warn('处理技能数据时出错:', error)
      continue
    }
  }

  return [...new Set(normalizedSkills)].filter(skill => skill.length > 1 && skill.length < 100)
}

const normalizedSkills = computed(() => {
  return normalizeSkillsData(
    rawSkillsData.value.length > 0 ? rawSkillsData.value : availableSkills.value,
  )
})

// 计算属性
const currentNode = computed(() => {
  return scriptNodes.find((node) => node.id === activeNodeId.value) || scriptNodes[0]
})

const currentCharacter = computed(() => {
  return characters.find((char) => char.id === activeCharacterId.value)
})

const currentCharacterBehaviors = computed(() => {
  if (!currentNode.value || !activeCharacterId.value) return []
  const settings = currentNode.value.characterSettings[activeCharacterId.value]
  return settings?.behaviors || []
})

// API连接检查
const checkApiConnection = async () => {
  try {
    const response = await apiClient.get('/health')
    if (response.data?.success) {
      apiConnected.value = true
      apiError.value = ''
    }
  } catch (error) {
    apiConnected.value = false
    apiError.value = 'AI服务连接失败，手动创作功能可正常使用'
  }
}

// 阶段显示名称
const getStageDisplayName = (stage: string) => {
  const stageNames = {
    analysis: '📊 需求分析',
    concept: '💡 概念构建',
    structure: '🏗️ 故事架构',
    characters: '👥 角色设计',
    skills: '⚔️ 技能体系',
    plot: '📖 剧情生成',
    optimization: '✨ 整体优化',
    complete: '✅ 生成完成',
  }

  return stageNames[stage as keyof typeof stageNames] || stage
}

// 🔧 重置相关方法
const confirmReset = () => {
  showResetModal.value = true
}

const closeResetModal = () => {
  showResetModal.value = false
}

const executeReset = () => {
  clearAllData()
  closeResetModal()
  console.log('🔄 数据已重置')
}

// 智能生成相关方法
const showIntelligentGenerator = () => {
  showIntelligentModal.value = true
}

const closeIntelligentModal = () => {
  showIntelligentModal.value = false
}

const startIntelligentGeneration = async () => {
  if (!intelligentRequest.user_input.trim()) {
    alert('请输入剧场描述')
    return
  }

  if (specialRequirementsText.value.trim()) {
    intelligentRequest.special_requirements = specialRequirementsText.value
      .split(',')
      .map((req) => req.trim())
      .filter((req) => req)
  }

  closeIntelligentModal()
  isIntelligentGenerating.value = true

  try {
    const response = await apiClient.post('/generate/intelligent', intelligentRequest)

    if (response.data.success) {
      const taskId = response.data.task_id

      const progressInterval = setInterval(async () => {
        try {
          const progressResponse = await apiClient.get(`/generate/progress/${taskId}`)
          const progressData = progressResponse.data.data

          generationProgress.progress = progressData.progress
          generationProgress.current_stage = progressData.current_stage
          generationProgress.message = progressData.message || ''

          if (progressData.status === 'completed') {
            clearInterval(progressInterval)
            const result = progressData.result

            updateGeneratedData(result)
            isIntelligentGenerating.value = false

            // 🎯 标记为AI生成的数据
            hasAIGeneratedData.value = true
            hasManualData.value = false
            lastUpdateTime.value = new Date()
            showEditInterface.value = true // 自动显示编辑界面

            alert('🎉 智能生成完成！')
          } else if (progressData.status === 'failed') {
            clearInterval(progressInterval)
            isIntelligentGenerating.value = false
            alert(`❌ 生成失败: ${progressData.error}`)
          }
        } catch (error) {
          console.error('获取进度失败:', error)
        }
      }, 2000)
    } else {
      throw new Error(response.data.message || '生成失败')
    }
  } catch (error: any) {
    isIntelligentGenerating.value = false
    alert(`❌ 启动生成失败: ${error.response?.data?.detail || error.message}`)
  }
}

const updateGeneratedData = (result: any) => {
  console.log('🔄 开始更新AI生成的数据...')

  try {
    if (result.theater_info) {
      Object.assign(theaterData, result.theater_info)
    }

    if (result.script_nodes && Array.isArray(result.script_nodes)) {
      scriptNodes.splice(0)
      scriptNodes.push(...result.script_nodes)
      activeNodeId.value = scriptNodes[0]?.id || 'node-1'
    }

    if (result.characters && Array.isArray(result.characters)) {
      characters.splice(0)
      characters.push(...result.characters)
      activeCharacterId.value = characters[0]?.id || 'char-1'
    }

    if (result.available_skills) {
      rawSkillsData.value = Array.isArray(result.available_skills)
        ? result.available_skills
        : [result.available_skills]

      const normalizedSkillsList = normalizeSkillsData(rawSkillsData.value)
      availableSkills.value = normalizedSkillsList

      characters.forEach((character) => {
        if (character.selectedSkills && character.selectedSkills.length > 0) {
          const normalizedSelectedSkills = normalizeSkillsData(character.selectedSkills)
          character.selectedSkills = normalizedSelectedSkills.filter((skill) =>
            availableSkills.value.includes(skill),
          )
        }
      })
    }

    console.log('🎉 AI生成数据更新完成!')
  } catch (error) {
    console.error('❌ 更新数据时出错:', error)
    alert('数据更新过程中遇到一些问题，但已尽可能保存了生成的内容。')
  }
}

// 基础操作方法
const goBack = () => {
  if (hasUserData.value) {
    if (confirm('您有未保存的修改，确定要离开吗？')) {
      router.push('/TheaterList')
    }
  } else {
    router.push('/TheaterList')
  }
}

const saveScript = () => {
  if (!hasUserData.value) {
    alert('没有可保存的数据')
    return
  }

  saveToLocalStorage()
  alert('剧情已保存！')
}

const publishTheater = () => {
  if (!hasUserData.value) {
    alert('没有可发布的数据')
    return
  }

  if (!theaterData.title.trim()) {
    alert('请先设置剧场名称')
    return
  }

  try {
    saveToLocalStorage()
    router.push('/TheaterDetail')
  } catch (error) {
    console.error('❌ 保存剧场数据失败:', error)
    alert('保存数据失败，请重试')
  }
}

const saveToLocalStorage = () => {
  if (!hasUserData.value) {
    alert('没有可保存的数据')
    return
  }

  const data = {
    theater_info: theaterData,
    script_nodes: scriptNodes,
    characters: characters,
    available_skills: availableSkills.value,
    raw_skills_data: rawSkillsData.value,
    generated_time: hasAIGeneratedData.value ? lastUpdateTime.value?.toISOString() : null,
    saved_time: new Date().toISOString(),
    data_source: hasAIGeneratedData.value ? 'ai' : 'manual',
    version: '2.5.0',
  }

  try {
    localStorage.setItem('theater_generated_data', JSON.stringify(data))
    alert('✅ 数据已保存到本地')
  } catch (error) {
    console.error('❌ 保存失败:', error)
    alert('❌ 保存失败，请重试')
  }
}

// 节点和角色操作
const selectNode = (nodeId: string) => {
  activeNodeId.value = nodeId
}

const selectCharacter = (characterId: string) => {
  activeCharacterId.value = characterId
}

const addNewNode = () => {
  const newId = `node-${Date.now()}`
  const newNode: ScriptNode = {
    id: newId,
    title: '新节点',
    content: '',
    characterSettings: {},
    level: 0,
  }
  scriptNodes.push(newNode)
  activeNodeId.value = newId
  onDataChange()
}

const addNewCharacter = () => {
  const characterName = prompt('请输入新角色名称:') || '新角色'
  const newId = `char-${Date.now()}`
  const newCharacter: Character = {
    id: newId,
    name: characterName,
    description: '请编辑角色描述...',
    avatar: `https://ui-avatars.com/api/?name=${encodeURIComponent(characterName)}&background=3b82f6&color=fff`,
    selectedSkills: [],
  }
  characters.push(newCharacter)
  activeCharacterId.value = newId
  onDataChange()
}

const updateContent = (event: Event) => {
  const target = event.target as HTMLDivElement
  if (currentNode.value) {
    currentNode.value.content = target.innerHTML
    onDataChange()
  }
}

const formatText = (command: string) => {
  document.execCommand(command, false, '')
  editorRef.value?.focus()
  onDataChange()
}

const toggleSkill = (skill: string) => {
  if (currentCharacter.value) {
    const skills = currentCharacter.value.selectedSkills
    const index = skills.indexOf(skill)

    if (index === -1) {
      if (typeof skill === 'string' && skill.trim().length > 0) {
        skills.push(skill.trim())
      }
    } else {
      skills.splice(index, 1)
    }

    currentCharacter.value.selectedSkills = [...skills]
    onDataChange()
  }
}

// 🔧 手动添加技能
const addManualSkill = () => {
  const skillName = prompt('请输入技能名称:')
  if (skillName && skillName.trim()) {
    const trimmedSkill = skillName.trim()
    if (!availableSkills.value.includes(trimmedSkill)) {
      availableSkills.value.push(trimmedSkill)
      onDataChange()
    } else {
      alert('该技能已存在')
    }
  }
}

const addBehavior = () => {
  const newBehavior = prompt('请输入新的行为:')
  if (newBehavior && newBehavior.trim() && currentNode.value) {
    if (!currentNode.value.characterSettings[activeCharacterId.value]) {
      currentNode.value.characterSettings[activeCharacterId.value] = {
        behaviors: [],
        conditions: [],
        branches: [],
      }
    }
    currentNode.value.characterSettings[activeCharacterId.value].behaviors.push(newBehavior.trim())
    onDataChange()
  }
}

const removeBehavior = (index: number) => {
  if (currentNode.value && currentNode.value.characterSettings[activeCharacterId.value]) {
    currentNode.value.characterSettings[activeCharacterId.value].behaviors.splice(index, 1)
    onDataChange()
  }
}

// 占位方法
const showScriptGenerator = () => {
  alert('请使用智能生成向导获得更好的体验')
}

const generateSingleCharacter = () => {
  alert('请使用智能生成向导生成完整的角色系统')
}

const optimizeContent = () => {
  alert('请使用智能生成向导获得AI优化的内容')
}
</script>

<style scoped>
.theater-app {
  --primary-blue: #3b82f6;
  --ai-gradient: linear-gradient(135deg, #8b5cf6, #ec4899);
  --ai-glow: 0 0 20px rgba(139, 92, 246, 0.3);

  margin: 0;
  padding: 2rem;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f7ff, #e6f3ff);
  color: #334155;
}

.container {
  max-width: 80vw;
  margin: 0 auto;
}

/* API状态横幅 */
.api-status-banner {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: linear-gradient(135deg, #ef4444, #dc2626);
  color: white;
  padding: 0.75rem;
  z-index: 1000;
  text-align: center;
}

.status-content {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
}

.retry-btn, .retry-small-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 0.5rem;
  cursor: pointer;
}

/* 顶部导航 */
.top-nav {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 1rem;
  padding: 1rem 2rem;
  margin-bottom: 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.1);
}

.nav-left {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.back-btn {
  background: none;
  border: none;
  color: var(--primary-blue);
  font-size: 1.2rem;
  cursor: pointer;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: rgba(59, 130, 246, 0.1);
}

.theater-name {
  font-size: 1.5rem;
  font-weight: 600;
  background: var(--ai-gradient);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

/* 数据状态指示器 */
.data-status {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  margin-left: 1rem;
}

.status-indicator {
  font-size: 0.8rem;
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  font-weight: 500;
}

.status-indicator.ai-generated {
  background: linear-gradient(135deg, rgba(139, 92, 246, 0.1), rgba(59, 130, 246, 0.1));
  color: #8b5cf6;
  border: 1px solid rgba(139, 92, 246, 0.3);
}

.status-indicator.manual-created {
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.1), rgba(5, 150, 105, 0.1));
  color: #059669;
  border: 1px solid rgba(16, 185, 129, 0.3);
}

.last-updated {
  font-size: 0.7rem;
  color: #64748b;
}

.nav-right {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.btn {
  padding: 0.75rem 1.5rem;
  border-radius: 0.75rem;
  border: none;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.btn-primary {
  background: var(--primary-blue);
  color: white;
}

.btn-success {
  background: linear-gradient(135deg, #10b981, #06b6d4);
  color: white;
}

.btn-secondary {
  background: rgba(255, 255, 255, 0.9);
  color: #334155;
  border: 1px solid #e2e8f0;
}

.btn-warning {
  background: linear-gradient(135deg, #f59e0b, #d97706);
  color: white;
}

.btn-danger {
  background: linear-gradient(135deg, #ef4444, #dc2626);
  color: white;
}

.btn-outline {
  background: transparent;
  color: var(--primary-blue);
  border: 2px solid var(--primary-blue);
}

.btn-outline:hover {
  background: var(--primary-blue);
  color: white;
}

.btn-small {
  padding: 0.5rem 1rem;
  font-size: 0.875rem;
}

.ai-btn {
  background: var(--ai-gradient);
  color: white;
  box-shadow: var(--ai-glow);
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(59, 130, 246, 0.15);
}

.ai-btn:hover {
  box-shadow: 0 6px 25px rgba(139, 92, 246, 0.4);
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

/* 🔧 欢迎引导界面增强 */
.welcome-guide {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 2rem;
  padding: 4rem 3rem;
  text-align: center;
  box-shadow: 0 8px 40px rgba(59, 130, 246, 0.1);
  border: 2px solid rgba(139, 92, 246, 0.1);
}

.guide-content {
  max-width: 900px;
  margin: 0 auto;
}

.guide-animation {
  position: relative;
  margin-bottom: 3rem;
}

.guide-icon {
  font-size: 5rem;
  margin-bottom: 1rem;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
}

.sparkles {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.sparkle {
  position: absolute;
  font-size: 1.5rem;
  animation: sparkle 2s ease-in-out infinite;
}

.sparkle-1 {
  top: 20%;
  left: 20%;
  animation-delay: 0s;
}

.sparkle-2 {
  top: 30%;
  right: 20%;
  animation-delay: 0.7s;
}

.sparkle-3 {
  bottom: 30%;
  left: 30%;
  animation-delay: 1.4s;
}

@keyframes sparkle {
  0%, 100% {
    opacity: 0;
    transform: scale(0.5) rotate(0deg);
  }
  50% {
    opacity: 1;
    transform: scale(1) rotate(180deg);
  }
}

.welcome-guide h2 {
  font-size: 2.5rem;
  font-weight: 700;
  background: var(--ai-gradient);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  margin-bottom: 1rem;
}

.guide-subtitle {
  font-size: 1.25rem;
  color: #64748b;
  margin-bottom: 3rem;
}

/* 🔧 创作选项卡片 */
.creation-options {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
  margin-bottom: 3rem;
}

.option-card {
  background: white;
  border-radius: 1.5rem;
  padding: 2rem;
  box-shadow: 0 8px 30px rgba(59, 130, 246, 0.1);
  border: 2px solid transparent;
  transition: all 0.4s ease;
  text-align: left;
}

.option-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(59, 130, 246, 0.15);
}

.ai-option {
  border-color: rgba(139, 92, 246, 0.2);
}

.ai-option:hover {
  border-color: #8b5cf6;
  box-shadow: 0 12px 40px rgba(139, 92, 246, 0.2);
}

.manual-option {
  border-color: rgba(59, 130, 246, 0.2);
}

.manual-option:hover {
  border-color: var(--primary-blue);
  box-shadow: 0 12px 40px rgba(59, 130, 246, 0.2);
}

.option-header {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
}

.option-icon {
  font-size: 2.5rem;
}

.option-header h3 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.option-desc {
  color: #64748b;
  font-size: 1rem;
  line-height: 1.6;
  margin-bottom: 1.5rem;
}

.option-features {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-bottom: 1.5rem;
}

.feature-tag {
  background: rgba(59, 130, 246, 0.1);
  color: var(--primary-blue);
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  font-size: 0.8rem;
  font-weight: 500;
}

.option-btn {
  width: 100%;
  padding: 1rem 1.5rem;
  font-size: 1rem;
  border-radius: 1rem;
}

/* 额外选项 */
.additional-options {
  margin-bottom: 3rem;
}

.stored-data-notice {
  background: linear-gradient(135deg, rgba(245, 158, 11, 0.1), rgba(217, 119, 6, 0.1));
  border: 2px solid rgba(245, 158, 11, 0.3);
  border-radius: 1rem;
  padding: 1.5rem;
  display: flex;
  align-items: center;
  gap: 1rem;
  justify-content: center;
}

.notice-icon {
  font-size: 1.5rem;
}

.notice-text {
  color: #d97706;
  font-weight: 500;
}

.guide-tips {
  background: linear-gradient(135deg, rgba(139, 92, 246, 0.05), rgba(59, 130, 246, 0.05));
  border-radius: 1rem;
  padding: 1.5rem;
  text-align: left;
}

.guide-tips h4 {
  color: #8b5cf6;
  margin-bottom: 1rem;
}

.guide-tips ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.guide-tips li {
  margin-bottom: 0.75rem;
  color: #64748b;
  padding-left: 1.5rem;
  position: relative;
}

.guide-tips li::before {
  content: '💡';
  position: absolute;
  left: 0;
  top: 0;
}

.api-status-check {
  margin-top: 2rem;
  padding: 1rem;
  background: rgba(245, 158, 11, 0.05);
  border-radius: 0.75rem;
  border: 1px solid rgba(245, 158, 11, 0.2);
}

.status-warning {
  display: flex;
  align-items: center;
  gap: 1rem;
  justify-content: center;
}

.warning-icon {
  font-size: 1.2rem;
}

.warning-text {
  color: #d97706;
  font-weight: 500;
}

/* 生成进度条 */
.generation-progress {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  margin-bottom: 2rem;
  box-shadow: 0 4px 20px rgba(139, 92, 246, 0.1);
  border: 2px solid #8b5cf6;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.progress-header h3 {
  background: var(--ai-gradient);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  margin: 0;
}

.progress-percentage {
  font-size: 1.5rem;
  font-weight: bold;
  color: #8b5cf6;
}

.progress-bar-container {
  width: 100%;
  height: 8px;
  background: rgba(139, 92, 246, 0.1);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 1rem;
}

.progress-bar {
  height: 100%;
  background: var(--ai-gradient);
  border-radius: 4px;
  transition: width 0.5s ease;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.9rem;
}

.current-stage {
  font-weight: 600;
  color: #8b5cf6;
}

.stage-message {
  color: #64748b;
  font-style: italic;
}

.generation-preview {
  margin-top: 1.5rem;
  padding: 1rem;
  background: #f8fafc;
  border-radius: 0.5rem;
  border-left: 4px solid #8b5cf6;
}

.generation-preview pre {
  max-height: 200px;
  overflow-y: auto;
  font-size: 0.8rem;
}

/* 主要内容区域 */
.content-area {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  gap: 2rem;
}

/* 侧边栏 */
.sidebar {
  background: white;
  border-radius: 1rem;
  padding: 1.5rem;
  height: fit-content;
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.08);
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.sidebar h2 {
  color: var(--primary-blue);
  font-size: 1.25rem;
  margin: 0;
}

.node-tree {
  margin-bottom: 1.5rem;
}

.root-node {
  font-weight: 600;
  color: #8b5cf6;
  margin-bottom: 1rem;
  font-size: 1.1rem;
}

.node-item {
  padding: 0.75rem;
  border-radius: 0.5rem;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 0.5rem;
}

.node-item:hover {
  background: rgba(59, 130, 246, 0.05);
}

.node-item.active {
  background: rgba(59, 130, 246, 0.1);
  color: var(--primary-blue);
  border-left: 3px solid var(--primary-blue);
}

.add-node, .add-role {
  width: 100%;
  padding: 0.75rem;
  border: 2px dashed var(--primary-blue);
  background: none;
  color: var(--primary-blue);
  border-radius: 0.5rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.add-node:hover, .add-role:hover {
  background: rgba(59, 130, 246, 0.05);
}

/* 空状态 */
.empty-state-small {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
  padding: 1.5rem;
  color: #94a3b8;
  font-size: 0.9rem;
}

.empty-icon {
  font-size: 2rem;
  opacity: 0.5;
}

.empty-text {
  font-style: italic;
}

/* 主内容区 */
.main-content {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.08);
}

/* 🔧 剧场信息编辑区 */
.theater-info-section {
  background: linear-gradient(135deg, rgba(139, 92, 246, 0.05), rgba(59, 130, 246, 0.05));
  border-radius: 1rem;
  padding: 1.5rem;
  margin-bottom: 2rem;
  border: 2px solid rgba(139, 92, 246, 0.1);
}

.theater-info-section h3 {
  color: #8b5cf6;
  margin-bottom: 1rem;
}

/* 节点编辑器 */
.node-editor {
  margin-bottom: 2rem;
}

.node-title {
  width: 100%;
  font-size: 1.8rem;
  font-weight: 600;
  color: var(--primary-blue);
  border: none;
  border-bottom: 2px solid rgba(59, 130, 246, 0.2);
  padding: 0.5rem 0;
  margin-bottom: 1.5rem;
  background: transparent;
  outline: none;
}

.node-title:focus {
  border-bottom-color: var(--primary-blue);
}

.editor-toolbar {
  background: rgba(59, 130, 246, 0.05);
  border-radius: 0.5rem;
  padding: 0.5rem;
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1.5rem;
  align-items: center;
}

.toolbar-btn {
  width: 36px;
  height: 36px;
  border: none;
  border-radius: 0.25rem;
  background: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.toolbar-btn:hover {
  background: rgba(59, 130, 246, 0.1);
}

.ai-optimize-btn {
  background: var(--ai-gradient);
  color: white;
  box-shadow: var(--ai-glow);
}

.toolbar-divider {
  width: 1px;
  height: 24px;
  background: rgba(59, 130, 246, 0.2);
  margin: 0 0.5rem;
}

.editor-content {
  min-height: 300px;
  padding: 1rem;
  border: 1px solid rgba(59, 130, 246, 0.2);
  border-radius: 0.5rem;
  line-height: 1.6;
}

.editor-content:focus {
  outline: none;
  border-color: var(--primary-blue);
}

.editor-content:empty::before {
  content: attr(placeholder);
  color: #94a3b8;
  font-style: italic;
}

/* 主内容空状态 */
.main-empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;
}

.empty-state-content {
  text-align: center;
  color: #64748b;
}

.empty-state-content .empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
  opacity: 0.5;
}

.empty-state-content h3 {
  color: #374151;
  margin-bottom: 0.5rem;
}

.empty-state-content p {
  margin-bottom: 1.5rem;
}

/* 角色设置 */
.character-settings {
  border-top: 1px solid #e2e8f0;
  padding-top: 1.5rem;
  margin-top: 2rem;
}

.character-settings h3 {
  color: var(--primary-blue);
  margin-bottom: 1rem;
}

.settings-section {
  margin-bottom: 1.5rem;
}

.settings-section h4 {
  color: #64748b;
  font-size: 1rem;
  margin-bottom: 0.5rem;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.tag {
  background: rgba(59, 130, 246, 0.1);
  color: var(--primary-blue);
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  font-size: 0.875rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.tag-remove {
  cursor: pointer;
  color: #dc2626;
}

.add-tag {
  background: none;
  border: 1px dashed var(--primary-blue);
  color: var(--primary-blue);
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  cursor: pointer;
  font-size: 0.875rem;
}

/* 角色管理 */
.role-list {
  margin-bottom: 1.5rem;
}

.role-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  border-radius: 0.5rem;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 0.5rem;
}

.role-item:hover {
  background: rgba(59, 130, 246, 0.05);
}

.role-item.active {
  background: rgba(59, 130, 246, 0.1);
  border-left: 3px solid var(--primary-blue);
}

.role-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: 2px solid var(--primary-blue);
}

.role-info {
  flex: 1;
}

.role-name {
  font-weight: 600;
  margin-bottom: 0.25rem;
}

.role-description {
  font-size: 0.875rem;
  color: #64748b;
}

.attribute-form {
  border-top: 1px solid #e2e8f0;
  padding-top: 1.5rem;
}

.attribute-form h3 {
  color: var(--primary-blue);
  margin-bottom: 1rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-label {
  display: block;
  font-weight: 500;
  color: #374151;
  margin-bottom: 0.5rem;
  font-size: 0.9rem;
}

.form-input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 0.5rem;
  transition: all 0.3s ease;
}

.form-input:focus {
  outline: none;
  border-color: var(--primary-blue);
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

/* 技能显示样式 */
.skill-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  max-height: 300px;
  overflow-y: auto;
  padding: 0.5rem;
  border: 1px solid #e2e8f0;
  border-radius: 0.5rem;
  background: #fafafa;
}

.skill-tag {
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--primary-blue);
  border-radius: 1rem;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
  color: var(--primary-blue);
  white-space: nowrap;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.skill-tag:hover {
  background: rgba(59, 130, 246, 0.1);
  transform: translateY(-1px);
}

.skill-tag.selected {
  background: var(--primary-blue);
  color: white;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.skill-placeholder {
  padding: 2rem 1rem;
  background: linear-gradient(135deg, rgba(139, 92, 246, 0.05), rgba(59, 130, 246, 0.05));
  border: 2px dashed #8b5cf6;
  border-radius: 0.75rem;
  text-align: center;
  color: #8b5cf6;
}

.skill-placeholder p {
  margin: 0.5rem 0;
  font-size: 0.9rem;
}

/* 智能模态框 */
.intelligent-modal {
  max-width: 600px;
  width: 90%;
}

.wizard-step {
  margin-bottom: 1.5rem;
}

.wizard-step h4 {
  color: #8b5cf6;
  margin-bottom: 0.75rem;
}

.large-textarea {
  min-height: 120px;
  resize: vertical;
}

.generation-tips {
  background: #f0f7ff;
  border-left: 4px solid #8b5cf6;
  padding: 1rem;
  border-radius: 0.5rem;
  margin-top: 1rem;
}

.generation-tips h5 {
  color: #8b5cf6;
  margin-bottom: 0.5rem;
}

.generation-tips ul {
  color: #64748b;
  font-size: 0.9rem;
  margin: 0;
  padding-left: 1.2rem;
}

.generation-tips li {
  margin-bottom: 0.25rem;
}

/* 重置模态框 */
.reset-modal {
  max-width: 500px;
  width: 90%;
}

.warning-content {
  text-align: center;
}

.warning-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.warning-text {
  color: #dc2626;
  font-weight: 500;
  margin-bottom: 1.5rem;
}

.data-summary {
  background: #f8fafc;
  border-radius: 0.5rem;
  padding: 1rem;
  text-align: left;
  border-left: 4px solid #f59e0b;
}

.data-summary h4 {
  color: #f59e0b;
  margin-bottom: 0.5rem;
}

.data-summary ul {
  margin: 0;
  color: #64748b;
}

/* 模态框通用样式 */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.modal {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #e2e8f0;
}

.modal-header h3 {
  background: var(--ai-gradient);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: #64748b;
  padding: 0.5rem;
  border-radius: 0.5rem;
  transition: all 0.3s ease;
}

.modal-close:hover {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

.modal-footer {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 1.5rem;
  padding-top: 1rem;
  border-top: 1px solid #e2e8f0;
}

/* 加载动画 */
.loading-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
  backdrop-filter: blur(4px);
}

.loading-content {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  text-align: center;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.loading-spinner {
  font-size: 2rem;
  animation: spin 2s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .content-area {
    grid-template-columns: 1fr;
    gap: 1rem;
  }

  .creation-options {
    grid-template-columns: 1fr;
  }

  .form-row {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .theater-app {
    padding: 1rem;
  }

  .container {
    max-width: 95vw;
  }

  .nav-right {
    flex-direction: column;
    gap: 0.5rem;
  }

  .welcome-guide {
    padding: 2rem 1.5rem;
  }
}
</style>
